import {getQiNiuToken,uploadNormalFile} from '@/api/QiuNiu'

export default {
  data() {
    return {
      myId: '',
      dataSource: [],
      cacheDataSource: [],
      total: 0,
      page: 1,
      size: 15,
      firstLoad: true,
      loading: false,
      searchForm: {},
      formVisibleRole: false,
      formVisible: false,
      isAdd: false,
      editId: '',
      formInfo: {},
      uploadData: {
        token: '',
        key: ''
      },
      fileName: '',
      img_url: 'https://upqiniu.tx2.isart.me/',
      formLoading: false,
      pagination: true,
      checkboxVals: []
    }
  },
  created() {
    this.town_id = JSON.parse(localStorage.getItem('userInfo')).town_id
    this.myId = JSON.parse(localStorage.getItem('userInfo')).id
  },
  mounted() {
    this.firstLoad && this.handleGetTable()
  },
  watch: {
    page() {
      this.handleGetTable()
    },
    size() {
      this.handleGetTable()
    },
    formVisible(val) {
      if (!val) {
        this.editId = ''
        this.handleResetForm()
      }
    }
    // editId: {
    //   handler(val) {
    //     if (val) {
    //       this.handleFindFormById()
    //     } else {
    //       this.handleAfterGetForm()
    //     }
    //   },
    //   immediate: true
    // }
  },
  methods: {
    /**
     * 上传图片前
     * @param file 文件流
     * @returns {Promise<void>}
     */
    async beforeAvatarUpload(file) {
      let token = await getQiNiuToken();
      const file_suffix = file.name.substr(file.name.lastIndexOf('.'))
      this.uploadData ={
        token,
        key: new Date().getTime() + Math.random().toString(36).slice(-8) + file_suffix,
      }
    },
    /**
     * 上传成功
     * @param response
     * @param file
     * @param fileList
     * @param type
     */
    upSuccess(response, file, fileList,type,index) {
      this.getFile(fileList,type,index)
    },
    /**
     * 删除图片
     * @param file
     * @param fileList
     * @param type
     */
    handleRemove(file, fileList,type,index) {
      this.deleteFile(fileList,type,index)
    },
    handleRectSearch() {
      this.searchForm = {}
      this.handleGetTable()
    },
    handleSetStatus(data) {
      const { id, status } = data
      this.changeStatus(id,status)
    },
    async handleFindFormById() {
      if (this.editId) {
        this.formLoading = true
        await get(this.findApi, { [this.markId]: this.editId }).then((res) => {
          if (res.code === 0) {
            this.formInfo = res.data
            this.handleAfterGetForm(res.data)
          }
        }).finally(() => {
          this.formLoading = false
        })
      }
    },
    handleSearchClick() {
      if (this.page !== 1) {
        this.page = 1
        return
      }
      this.handleGetTable()
      // TODO 其他逻辑
    },
    handleOpenRole(data) {
      this.$set(this.formInfo, 'id', data.id)
      this.$set(this.formInfo, 'role', data.role)
      this.formVisibleRole = true
    },
    /**
     * 打开弹窗
     * @param {string} formId
     * @param {*[]} editCon
     * @param data
     */
    handleOpenForm(formId = '', editCon = [], data = {}) {
      formId === '' ? this.formInfo = {} : ''
      this.formVisible = true
      this.isAdd = !formId
      this.editId = formId
      if (editCon && !this.isAdd) {
        editCon.forEach((item) => {
          this.$set(this.formInfo, item, data[item])
        })
      }
      console.log(this.formInfo)
    },
    // 获取列表数据
    async handleGetTable() {
      this.loading = true
      const isPage = this.pagination ? {} : { is_paginate: 0 }
      const searchForm = JSON.parse(JSON.stringify(this.searchForm))

      this.handleBeforeGetTable(searchForm)
      // 这里不触发视图更新
      delete searchForm.admin
      await this.getList()
    },
    handleActionSaveForm() {
      const idSend = !this.isAdd ? { [this.markId]: this.editId } : {}
      this.handleBeforeSubmit()
      this.createManager(idSend)
    },
    // 保存表单
    handleSaveForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.handleActionSaveForm()
        } else {
          this.handleResetDialog()
        }
      })
    },
    handleResetDialog() {
      this.$refs['wx-dialog'].disabled = true
    },
    /**
     * 删除
     * @param {string} formId
     */
    handleDelByKey(formId) {
      this.loading = true
      post(`${this.baseApi}deleteById`, { [this.markId]: formId }).then((res) => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.handleGetTable()
        }
      }).finally(() => {
        this.loading = false
      })
    },
    handleResetForm() {
      this.$nextTick(() => {
        this.formInfo = {}
        this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
      })
    },
    /**
     * @status number 变更值
     * @id string id
     * @index number
     */
    handleSwitchStatus(status, id, index) {
      console.log()
      // this.loading = true
      // post(`${this.baseApi}setStatus`, { [this.markId]: id, status }).then((res) => {
      //   if (res.code === 200) {
      //     this.$message.success(status === 0 ? '关闭成功' : '启用成功')
      //     this.handleGetTable()
      //   } else {
      //     this.$set(this.dataSource[index], 'status', status === 0 ? 1 : 0)
      //   }
      // }).finally(() => {
      //   this.loading = false
      // })
    },
    /**
     * 多删除
     */
    handleDelByIds() {
      if (!this.checkboxVals.length) {
        this.$message.warning('请最少选择一项进行删除操作！')
        return
      }
      const ids = this.checkboxVals.map((item) => item.id).join(',')
      this.$confirm('此操作将删除所选的信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        post(`${this.baseApi}batchDelete`, { [`${this.markId}s`]: ids }).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.handleGetTable()
          }
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    },
    /**
     * 提交前处理函数
     */
    handleBeforeSubmit() {
    },
    /**
     * 获取表单后
     */
    handleAfterGetForm() {
    },
    /**
     * 表格获取后
     */
    handleCompleteTable() {
    },
    /**
     * 获取表单前
     */
    handleBeforeGetTable() {
    }
  }
}
